﻿using HuaTong.General.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindGoes6;
using WindGoes6.Controls;
using WindGoes6.Data;
using WindGoes6.Forms;
using WindGoes6.Security;
using WindGoes6.Sys;
using WindGoes6.Utils;

namespace TestProject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void BtnCSVHelperTest_Click(object sender, EventArgs e)
        {
            // 先读取 
            _CSVHelper csv = new _CSVHelper(Common.GetDataPath(@"CSV\coma_quotes.csv"));
            List<List<string>> data = csv.GetListCsvData();

            foreach (var item in data)
            {
                foreach (var sub in item)
                {
                    Console.Write(sub + "\t\t");
                }
                Console.WriteLine();
            }
            Console.WriteLine();


            // 再保存后读取新文件，确认保存的结果正常。 
            _CSVHelper.SaveCsvFile(Common.GetDataPath(@"CSV\coma_quotes1.csv"), data);
        }

        private void btnCSVTest_Click(object sender, EventArgs e)
        {
            CSV csv = new CSV(Common.GetDataPath(@"CSV\coma_quotes.csv"));
            for (int row = 0; row < csv.RowCount; row++)
            {
                for (int column = 0; column < csv.ColumnCount; column++)
                {
                    Console.Write(csv[row, column] + ", ");
                }
                Console.WriteLine();
            }
            csv[1, 1] = "jack";
            csv.Save(Common.GetDataPath("data1.csv"));
        }

        BalloonTip m_tip = new BalloonTip();
        private void BtnBalloonTest_Click(object sender, EventArgs e)
        {
            Point pos = this.btnBalloonTest.PointToScreen(new Point(10, 10));
            this.m_tip.ShowAt(pos.X, pos.Y, "Title", "Content", BalloonTipIconType.Information);
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            TextBoxButton tbb = new TextBoxButton(textBox1, false);
            tbb.ButtonText = "测试";
            tbb.Click += tbb_Click;
        }

        private void tbb_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Test");
        }

        private void Btn_DosInvoker_Click(object sender, EventArgs e)
        {
            //Console.WriteLine(DosInvoker.RunDosCommand("dir", "*.exe"));

            //foreach (var file in Directory.GetFiles("."))
            //{
            //    string fullpath = Path.GetFullPath(file);
            //    string sha1 = DosInvoker.RunDosCommand("certutil", "-hashfile", fullpath, "SHA1").Split('\n')[1].Trim('\r');
            //    Console.WriteLine($"The SHA1 of {fullpath} is {sha1}.");
            //}
        }

        private void BtnCommandCommandTest_Click(object sender, EventArgs e)
        {
            //string result1 = DosInvoker.RunDosCommand(@"..\data\pdf.exe", @"merge -i ..\data\test.pdf -o output1.pdf -arg 1,3,5");
            //Console.WriteLine(result1);
            //string result2 = DosInvoker.RunCommand(@"..\data\pdf.exe", 3, @"merge -i ..\data\test.pdf -o output2.pdf -arg 2,4,6");
            //Console.WriteLine(result2);
        }

        private void BtnHardwareInfo_Click(object sender, EventArgs e)
        {
            Console.WriteLine("CPU: " + ComputerInfo.GetCPUInfo());
            Console.WriteLine("MB: " + ComputerInfo.GetMotherBoardInfo());
            Console.WriteLine("MAC: " + ComputerInfo.GetMacAddress());





            Console.WriteLine("GetCPUNumber: " + MachineNumber.GetCPUNumber());
            Console.WriteLine("GetHardDiskNumberr: " + MachineNumber.GetHardDiskNumber());
            Console.WriteLine("GetMemoryNumber: " + MachineNumber.GetMemoryNumber());
            Console.WriteLine("HardDiskInfo: " + MachineNumber.HardDiskInfo());
            Console.WriteLine("MemoryInfo: " + MachineNumber.MemoryInfo());
            // Console.WriteLine("NetworkInfo: " + MachineNumber.NetworkInfo());
            Console.WriteLine("OSInfo: " + MachineNumber.OSInfo());



        }

        private void BtnConFormTest_Click(object sender, EventArgs e)
        {
            ConTestForm ctf = new ConTestForm();
            ctf.ShowDialog();

            if (ctf.Connected)
            {
                MessageBox.Show("Test");
            }
        }

        private void BtnXMLDemo_Click(object sender, EventArgs e)
        {
            new XMLDemo().ReadTest();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 0;
            int count = tabControl1.TabCount;
            for (int i = 1; i < count; i++)
            {
                //tabControl1.TabPages.RemoveAt(1);
            }
        }

        private void BtnAnalyzeNovel_Click(object sender, EventArgs e)
        {
            new Novel().ReadTest();
        }

        private void BtnCommandCommandParamterTest_Click(object sender, EventArgs e)
        {
           // string s1 = @"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2019\Visual Studio Tools\Developer Command Prompt for VS 2019 Preview.lnk";
           // Console.WriteLine(DosInvoker.RunCommands("\"" + s1 + "\"", "S:", @"cd TemporaryProjects\ManifestDemo", "msbuild", @"cd bin\Debug && dir"));

        }

        private void BtnFortuneSimulator_Click(object sender, EventArgs e)
        {
            new FortuneSimilator().Test();
        }

        private void BtnXMLWrite_Click(object sender, EventArgs e)
        {
            new XMLDemo().WriteTest();
        }

        private void btnAESTest_Click(object sender, EventArgs e)
        {
            string text = "平台安全保障模块确保数据的接入、传输和存储安全，满足数据的机密性、完整性和可应性要求。平台安全保障模块主要包括业务安全，传输安全和存储安全。";
            string pubkey = "testtesttesttest";
            string text1 = AES.AESEncrypt(text, pubkey);
            string text2 = AES.AESDecrypt(text1, pubkey);
            Console.WriteLine($"Before: {text}");
            Console.WriteLine($"Encrypt: {text1}");
            Console.WriteLine($"After: {text2}");

            //            Console.WriteLine("解密" + AES.Decrypt("/4+UJG55uVHN6rninZ6Z8nUe2OJHGGAYqcdmdDeQhiM=", key));
            //            Console.ReadLine();
        }

        private void btnMoveScroll_Click(object sender, EventArgs e)
        {
            panelScrollTest.VerticalScroll.Value = panelScrollTest.VerticalScroll.Maximum;
        }

        private void BtnGetOSVersion_Click(object sender, EventArgs e)
        {
            int ptid = (int)Environment.OSVersion.Platform; //获取操作系统ID 
            int majorid = Environment.OSVersion.Version.Major; //获取主版本号 
            int minorid = Environment.OSVersion.Version.Minor; //获取副版本号
            int build = Environment.OSVersion.Version.Build;
            string vinfo = ptid.ToString("00") + majorid.ToString("00") + minorid.ToString("00");
            vinfo = $"{ptid}.{majorid}.{minorid}.{build}";
            // MessageBox.Show($"PlatformID = {platformID}, VersionMajor ={versionMajor}, versionMinor = {versionMinor}.");


            StringBuilder sb = new StringBuilder();
            sb.AppendLine("计算机名:" + SystemInformation.ComputerName);
            sb.AppendLine("计算机名:" + Environment.MachineName);
            sb.AppendLine("操作系统:" + Environment.OSVersion.Platform);
            sb.AppendLine("版本号:" + Environment.OSVersion.VersionString);
            sb.AppendLine("处理器个数:" + Environment.ProcessorCount);
            sb.AppendLine("操作系统位数:" + (Environment.Is64BitOperatingSystem ? 64 : 32) + "bit.");
            sb.AppendLine("网络连接: " + (SystemInformation.Network ? "已连接" : "未连接"));

            //判断启动模式
            if (SystemInformation.BootMode.ToString() == "Normal")
                sb.AppendLine("启动模式:正常启动");
            if (SystemInformation.BootMode.ToString() == "FailSafe")
                sb.AppendLine("启动模式:安全启动");
            if (SystemInformation.BootMode.ToString() == "FailSafeWithNework")
                sb.AppendLine("启动方式:通过网络服务启动");


            sb.AppendLine("显示器数量:" + SystemInformation.MonitorCount);
            sb.AppendLine("显示器分辨率:" + SystemInformation.PrimaryMonitorMaximizedWindowSize.Width + " x " + SystemInformation.PrimaryMonitorMaximizedWindowSize.Height);
            sb.AppendLine("主显示器当前分辨率:" + SystemInformation.PrimaryMonitorSize.Width + " x " + SystemInformation.PrimaryMonitorSize.Height);
            sb.AppendLine("鼠标按钮个数:" + SystemInformation.MouseButtons.ToString());//不知道怎么获取出来的是5个按钮
            sb.AppendLine("系统限定目录:" + Environment.SystemDirectory);
            sb.AppendLine("系统内存:" + Environment.SystemPageSize.ToString());


            // MessageBox.Show($"{sb}");

            string cpuInfo = "";
            string addressWidth = "";

            //cpu序列号
            ManagementClass cimobject = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = cimobject.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                addressWidth = mo.Properties["AddressWidth"].Value.ToString();
                cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                sb.AppendFormat("cpu序列号：{0}\n", cpuInfo);
            }

            //获取硬盘ID
            String HDid;
            ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection moc1 = cimobject1.GetInstances();
            foreach (ManagementObject mo in moc1)
            {
                HDid = (string)mo.Properties["Model"].Value;
                sb.AppendFormat("硬盘序列号：{0}\n", HDid);
            }

            //获取网卡硬件地址
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc2 = mc.GetInstances();
            foreach (ManagementObject mo in moc2)
            {
                if ((bool)mo["IPEnabled"] == true)
                    sb.AppendFormat("网卡地址：{0}\n", mo["MacAddress"].ToString());
            }

            sb.AppendFormat("{0} {1}位 {2}核\n", Environment.OSVersion.VersionString, addressWidth, Environment.ProcessorCount);

            MessageBox.Show(sb.ToString());

            Version currentVersion = Environment.OSVersion.Version;
            //OS版本号
            Console.WriteLine("Major:{0}", currentVersion.ToString());
            //OS版本号的主要版本号
            Console.WriteLine("Major:{0}", currentVersion.Major);
            //OS版本号的次要版本号
            Console.WriteLine("Minor:{0}", currentVersion.Minor);
            //OS版本号的内部版本号
            Console.WriteLine("Build:{0}", currentVersion.Build);
            //OS版本号的修订部分的值
            Console.WriteLine("Revision:{0}", currentVersion.Revision);
            //OS版本号的修订号的高16位
            Console.WriteLine("MajorRevision:{0}", currentVersion.MajorRevision);
            //OS版本号的修订号的低16位
            Console.WriteLine("MinorRevision:{0}", currentVersion.MinorRevision);
        }

        private void BtnGetSystemInformation_Click(object sender, EventArgs e)
        {
            //string info = WindGoes6.Sys.DosInvoker.RunDosCommand("systeminfo");
            //MessageBox.Show(info);
            //// http://106.12.6.198:13071/WebApi/WebApi?api=info&imei=864768013300113&arg=20190419
        }

        private void BtnInvokeWebApi_Click(object sender, EventArgs e)
        {
            string info = DosInvoker.RunDosCommand("systeminfo", "");
            info = info.Replace("\r", "").Replace("\n", "<br>");
            info = Common.TranslateInfo(info);
            if (info.Length * 2 < 4096)
                info += new string('.', 4096 - info.Length * 2);

            info = Convert.ToBase64String(Encoding.UTF8.GetBytes(info)).Replace("+", "-").Replace("/", "_");

            string url = $"http://106.12.6.198:13071/WebApi/QDasApi";
            string convertid = "T201904";
            string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string verstion = "alpha1";
            string param = $"api=sysinfo&key={convertid}_{verstion}_{datetime}&arg1={info}&arg2={info}&arg3={info}";
            StringBuilder sb = new StringBuilder();
            sb.Append(param);
            for (int i = 4; i < 520; i++)
            {
                sb.Append($"&arg{i}={info}");
            }
            param = sb.ToString();
            Console.WriteLine(param.Length);

            string pagehtml = WindGoes6.Web.WebApiInvoker.InvokeWebApiPost(url, param);
            string outhtml = "C:\\data\\test.html";
            File.WriteAllText(outhtml, pagehtml, Encoding.UTF8);
            Process.Start(outhtml);
        }

        private void btnSendFilePartHttp_Click(object sender, EventArgs e)
        {
            byte[] bts = Common.ReadFilePart("Spire.XLS.dll", 0, 3 * 1024 * 1024);
            string url = $"http://106.12.6.198:13071/WebApi/QDasApi";
            string info = Convert.ToBase64String(bts).Replace("+", "-").Replace("/", "_");
            string param = $"api=filepart&key=file20190422&arg1={info}";
            string pagehtml = WindGoes6.Web.WebApiInvoker.InvokeWebApiPost(url, param, 100000);
            string outhtml = "C:\\data\\test1.html";
            File.WriteAllText(outhtml, pagehtml, Encoding.UTF8);
            Process.Start(outhtml);
        }

        private void BtnConfigAccessTest_Click(object sender, EventArgs e)
        {
            string s = "this is test for breakline.";
            int i = 10;
            float f = 1.2f;
            double d = 232.3234;
            DateTime dt = DateTime.Now;

            ConfigAccess ca = new ConfigAccess("config.ini");
            ca.SetValue("s", s);
            ca.SetValue("System.s", s);
            ca.SetValue("System.IO", "s", s);
            ca.SetValue("System.IO", "s", s);

            ca.SetValue("i", i.ToString());
            ca.SetValue("d", d.ToString());
            ca.SetValue("f", f.ToString());
            ca.SetValue("dt", dt.ToString());
            ca.Save();


            ca = new ConfigAccess("config.ini");
            Console.WriteLine(ca.GetString("s"));
            Console.WriteLine("System.s: " + ca.GetString("System", "s", null));
            Console.WriteLine("System.s: " + ca.GetString("System", "s", null));
            Console.WriteLine("System.IO.s: " + ca.GetString("System.IO", "s", null));

            Console.WriteLine(ca.GetString("s"));
            Console.WriteLine(ca.GetInt("i"));
            Console.WriteLine(ca.GetDouble("d"));
            Console.WriteLine(ca.GetFloat("f"));
            Console.WriteLine(ca.GetDateTime("dt"));
        }

        private void BtnDosCommondTest_Click(object sender, EventArgs e)
        {
            txtCommondResult.Text = DosInvoker.RunDosCommand(txtDosCommand.Text);

            //foreach (var file in Directory.GetFiles("."))
            //{
            //    string fullpath = Path.GetFullPath(file);
            //    certutil -hashfile c:\data\a.txt SHA1
            //    $"certutil -hashfile {Path.GetFullPath(file)} SHA1"
            //    string sha1 = ConsoleInvoker.RunDosCommand("certutil", "-hashfile", fullpath, "SHA1").Split('\n')[1].Trim('\r');
            //    Console.WriteLine($"The SHA1 of {fullpath} is {sha1}.");
            //}
        }

        private void TxtDosCommand_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnDosCommondTest.PerformClick();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string java = "\"c:\\Program Files\\Java\\jdk1.8.0_191\\bin\\java.exe\"";
            string args = "-cp c:\\data\\BaseX921.jar org.basex.BaseX -c \"xquery db:open('te')//*\"";

            Console.WriteLine(java + " " + args);
            Process p = new Process();
            p.StartInfo.FileName = java;
            p.StartInfo.Arguments = args;
            p.StartInfo.UseShellExecute = false; // 不显示用户界面
            p.StartInfo.RedirectStandardOutput = true; // 是否重
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.StandardOutputEncoding = Encoding.Default;
            // 返回数据
            string output = "";
            try
            {
                if (p.Start())//开始进程  
                {
                    // p.WaitForExit(); //等待进程结束，等待时间为指定的毫秒  
                    output = p.StandardOutput.ReadToEnd();//读取进程的输出  
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);//捕获异常，输出异常信息
            }
            finally
            {
                if (p != null)
                    p.Close();
            }
            Console.WriteLine(output);

            //string result1 = ConsoleInvoker.RunDosCommand(@"..\data\pdf.exe", @"merge -i ..\data\test.pdf -o output1.pdf -arg 1,3,5");
            //Console.WriteLine(result1);
            //string result2 = ConsoleInvoker.RunCommand(@"..\data\pdf.exe", 3, @"merge -i ..\data\test.pdf -o output2.pdf -arg 2,4,6");
            //Console.WriteLine(result2);
        }


        ConfigAccess ca = new ConfigAccess("config.ini");
        private void BtnReadConfig_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            foreach (var item in ca.GetKeys())
                dataGridView1.Rows.Add();

            for (int i = 0; i < ca.GetKeys().Count; i++)
            {
                string key = ca.GetKeys()[i];
                dataGridView1.Rows[i].Cells[0].Value = key;
                dataGridView1.Rows[i].Cells[1].Value = ca.GetString(key);
            } 
        }

        private void BtnWriteConfig_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView1.RowCount - 1; i++)
            {
                string key = dataGridView1.Rows[i].Cells[0].Value.ToString();
                string value = dataGridView1.Rows[i].Cells[1].Value.ToString();
                if (key == null || key.Trim().Length == 0)
                    continue;
                ca.SetValue(key, value);
            }
            ca.Save();
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            ConfigAccess ca = new ConfigAccess();
            ca.Load();

        }
    }
}
